package com.gaoyi.websocket.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gaoyi.websocket.common.GaoYiWebSocketServer;
import com.gaoyi.websocket.entity.Message;
import com.gaoyi.websocket.mapper.MessageMapper;
import com.gaoyi.websocket.service.MessageService;
import com.gaoyi.websocket.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

import static com.gaoyi.websocket.controller.ChatController.SERVER;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liaojunhui
 * @since 2021-05-27
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    @Resource
    RedisUtils redisUtils;
    @Resource
    MessageMapper messageMapper;
    @Resource
    RedisTemplate redisTemplate;

    public static final String OWNER = "MESSAGE_";
    public static final String LATEST_MSG = "LATEST";

    //保存消息
//    @Override
//    public Future<Boolean> saveObjMessage(String sendId, Message message) throws IOException {
//        int res = redisUtils.lPush(OWNER + sendId,message);
//        //记录此人id到给我发过消息的人集合,没有就插入，有就更新最后一条信息
//        redisUtils.hmSet(LATEST_MSG,sendId,message);
//        return res > 0 ? new AsyncResult<>(true) : new AsyncResult<>(false);
//    }

    //查询给我发过的消息
    @Override
    public Map queryUsedMsg(int pageNo, int pageSize, String id) {
        Map resMap = new HashMap();

        //查询所有
        if (id == null || id == ""){
            Map<String,Message> userMap = redisTemplate.opsForHash().entries(LATEST_MSG);
            List<Map.Entry<String,Message>> messageList = new ArrayList<>(userMap.size());
            messageList.addAll(userMap.entrySet());
            resMap.put("users",messageList.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList()));
            resMap.put("totalSize",userMap.size());

        //查询关于某个用户的所有互动消息
        }else {
            List<Object> messageList = redisUtils.lRange(OWNER + id,0,-1);      //redis中的消息
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("sendId",id);
            List<Message> messagesListFormMysql = messageMapper.selectList(wrapper);    //mysql中的消息
            messageList.addAll(messagesListFormMysql);                                  //合并
            resMap.put("messages",messageList.stream().skip((pageNo -1) * pageSize).limit(pageSize).collect(Collectors.toList()));
            resMap.put("totalSize",messageList.size());
        }
        resMap.put("currentPage",pageNo);
        return resMap;
    }

    //遍历在线用户
    @Override
    public Map scanOnlineUsers(int pageNo, int pageSize) {
        Map resMap = new HashMap();
        Set<String> onlineUsers = GaoYiWebSocketServer.userPools.keySet();
        resMap.put("users",onlineUsers.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList()));
        resMap.put("totalSize",onlineUsers.size());
        resMap.put("currentPage",pageNo);
        return resMap;
    }
}

































